<script setup lang="ts">
import {onMounted, ref, watch} from "vue";
import {getCourseAssignmentList} from "../apis/CourseAssignmentApi.ts";
import {ElMessage} from "element-plus";
import {getCourseSelectionCount} from "../apis/CourseSelectionApi.ts";
import {getCourseById} from "../apis/CourseApi.ts";
//学生选课情况柱状图
const props = defineProps({
  depId:{
    type: String,
    required: true
  }
})

//图标dom实例
const barChart = ref(null)
const optionBar = ref({
  title: {
    text: '各课程选课人数'
  },
  xAxis: {
    type: 'category',
    data: []
  },
  yAxis: {
    type: 'value'
  },
  series: [
    {
      data: [],
      type: 'bar'
    }
  ]
})
const getData = async () => {

  optionBar.value.xAxis.data = []
  optionBar.value.series[0].data = []
  //获取该学院下的所有课程
  const depRes = await getCourseAssignmentList(props.depId)
  if (depRes.flag){
    //获取每个课程的选课人数
    for (let i = 0; i < depRes.data.length; i++) {
      //获取课程信息
      const courseRes = await getCourseById(depRes.data[i].courseId)
      const courseNumRes = await getCourseSelectionCount(depRes.data[i].courseId,props.depId)
      if (courseRes.flag){
        optionBar.value.xAxis.data.push(courseRes.data.name)
        optionBar.value.series[0].data.push(courseNumRes.data)
      }else{
        ElMessage.error(courseRes.msg)
      }
    }
    console.log(optionBar.value)

  }else{
    ElMessage.error(depRes.msg)
  }
}

watch(() => props.depId, async (newVal) => {
  await getData()
  barChart.value.setOption(optionBar.value,true)
})
onMounted(async () => {
})
</script>

<template>
  <v-chart ref="barChart" autoresize  class="chart" :option="optionBar"></v-chart>
</template>

<style scoped>
.chart{
  width: 100%;
  height: 80%;
}
</style>